<template>
  <div class="tool-page">
    <div class="tool-header">
      <h1>图片格式转换工具</h1>
      <p>转换图片格式，支持JPG、PNG、WebP等</p>
    </div>
    
    <div class="image-convert">
      <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop.prevent="onFileDrop">
        <input 
          type="file" 
          ref="fileInput" 
          @change="onFileChange" 
          accept="image/*" 
          multiple 
          class="file-input" 
        />
        <div class="upload-icon">
          <span class="icon">🔄</span>
        </div>
        <p class="upload-text">点击或拖拽图片到此处</p>
        <p class="upload-hint">支持JPG、PNG、GIF、WebP等格式</p>
      </div>
      
      <div class="conversion-settings" v-if="files.length > 0">
        <h3>转换设置</h3>
        <div class="form-group">
          <label for="output-format">输出格式：</label>
          <select id="output-format" v-model="outputFormat" class="form-control">
            <option value="jpeg">JPEG</option>
            <option value="png">PNG</option>
            <option value="webp">WebP</option>
          </select>
        </div>
        <div class="form-group" v-if="outputFormat === 'jpeg'">
          <label for="quality">JPEG质量：{{ quality }}%</label>
          <input 
            type="range" 
            id="quality" 
            v-model="quality" 
            min="10" 
            max="100" 
            step="5" 
            class="quality-slider" 
          />
        </div>
        <div class="form-group">
          <label>
            <input type="checkbox" v-model="resizeImage" />
            调整图片尺寸
          </label>
        </div>
        <div class="form-group" v-if="resizeImage">
          <label for="max-width">最大宽度：{{ maxWidth }}px</label>
          <input 
            type="range" 
            id="max-width" 
            v-model="maxWidth" 
            min="100" 
            max="4000" 
            step="100" 
            class="quality-slider" 
          />
        </div>
      </div>
      
      <div class="file-list" v-if="files.length > 0">
        <h3>待转换图片 ({{ files.length }})</h3>
        <div class="file-item" v-for="(file, index) in files" :key="index">
          <div class="file-preview">
            <img :src="file.preview" alt="预览" />
          </div>
          <div class="file-info">
            <div class="file-name">{{ file.name }}</div>
            <div class="file-size">{{ formatFileSize(file.size) }} | {{ file.type.split('/')[1].toUpperCase() }}</div>
          </div>
          <button @click="removeFile(index)" class="btn remove-btn">删除</button>
        </div>
        
        <div class="actions">
          <button @click="convertImages" class="btn primary">开始转换</button>
          <button @click="clearFiles" class="btn danger">清空</button>
        </div>
      </div>
      
      <div class="result-list" v-if="results.length > 0">
        <h3>转换结果</h3>
        <div class="result-item" v-for="(result, index) in results" :key="index">
          <div class="result-preview">
            <img :src="result.dataUrl" alt="转换后预览" />
          </div>
          <div class="result-info">
            <div class="result-name">{{ result.name }}</div>
            <div class="result-details">
              <span>{{ formatFileSize(result.size) }}</span>
              <span>{{ result.dimensions.width }} × {{ result.dimensions.height }}</span>
              <span>{{ result.format.toUpperCase() }}</span>
            </div>
          </div>
          <button @click="downloadImage(result)" class="btn download-btn">下载</button>
        </div>
        
        <div class="batch-actions" v-if="results.length > 1">
          <button @click="downloadAllImages" class="btn primary">下载全部</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ImageConvert',
  data() {
    return {
      files: [],
      results: [],
      outputFormat: 'jpeg',
      quality: 90,
      resizeImage: false,
      maxWidth: 1920
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    onFileChange(event) {
      this.addFiles(event.target.files);
    },
    onFileDrop(event) {
      this.addFiles(event.dataTransfer.files);
    },
    addFiles(fileList) {
      for (let i = 0; i < fileList.length; i++) {
        const file = fileList[i];
        if (file.type.startsWith('image/')) {
          const reader = new FileReader();
          reader.onload = (e) => {
            this.files.push({
              file: file,
              name: file.name,
              size: file.size,
              type: file.type,
              preview: e.target.result
            });
          };
          reader.readAsDataURL(file);
        }
      }
    },
    removeFile(index) {
      this.files.splice(index, 1);
    },
    clearFiles() {
      this.files = [];
      this.results = [];
    },
    convertImages() {
      if (this.files.length === 0) return;
      
      this.results = [];
      
      this.files.forEach(fileObj => {
        const img = new Image();
        img.onload = () => {
          const canvas = document.createElement('canvas');
          let width = img.width;
          let height = img.height;
          
          // 调整尺寸
          if (this.resizeImage && width > this.maxWidth) {
            const ratio = this.maxWidth / width;
            width = this.maxWidth;
            height = Math.round(height * ratio);
          }
          
          canvas.width = width;
          canvas.height = height;
          
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0, width, height);
          
          // 转换图片格式
          const mimeType = `image/${this.outputFormat}`;
          const quality = this.outputFormat === 'jpeg' ? this.quality / 100 : 1;
          const dataUrl = canvas.toDataURL(mimeType, quality);
          
          // 计算转换后大小
          const size = Math.round((dataUrl.length * 3) / 4) - 
            (dataUrl.endsWith('==') ? 2 : dataUrl.endsWith('=') ? 1 : 0);
          
          // 生成新文件名
          const originalName = fileObj.name.replace(/\.[^/.]+$/, '');
          const newName = `${originalName}.${this.outputFormat}`;
          
          this.results.push({
            name: newName,
            dataUrl: dataUrl,
            size: size,
            format: this.outputFormat,
            dimensions: {
              width: width,
              height: height
            }
          });
        };
        img.src = fileObj.preview;
      });
    },
    downloadImage(result) {
      const link = document.createElement('a');
      link.href = result.dataUrl;
      link.download = result.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    downloadAllImages() {
      // 在实际项目中，可以使用JSZip等库将所有图片打包下载
      this.results.forEach((result, index) => {
        setTimeout(() => {
          this.downloadImage(result);
        }, index * 500); // 延迟下载，避免浏览器阻止多个下载
      });
    },
    formatFileSize(bytes) {
      if (bytes < 1024) {
        return bytes + ' B';
      } else if (bytes < 1024 * 1024) {
        return (bytes / 1024).toFixed(2) + ' KB';
      } else {
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
      }
    }
  }
}
</script>

<style scoped>
.image-convert {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.upload-area {
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.05);
}

.file-input {
  display: none;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: var(--primary-color);
}

.upload-text {
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
  color: var(--secondary-color);
}

.upload-hint {
  color: var(--text-light);
  font-size: 0.9rem;
}

.conversion-settings {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 1.5rem;
}

.conversion-settings h3 {
  margin-bottom: 1rem;
  color: var(--secondary-color);
}

.quality-slider {
  width: 100%;
  margin-top: 0.5rem;
}

.file-list, .result-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.file-list h3, .result-list h3 {
  margin-bottom: 0.5rem;
  color: var(--secondary-color);
}

.file-item, .result-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 0.75rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.file-preview, .result-preview {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 1rem;
}

.file-preview img, .result-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-info, .result-info {
  flex: 1;
}

.file-name, .result-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.file-size, .result-details {
  font-size: 0.9rem;
  color: var(--text-light);
}

.result-details span {
  margin-right: 1rem;
}

.remove-btn, .download-btn {
  padding: 0.25rem 0.75rem;
  font-size: 0.9rem;
}

.remove-btn {
  background-color: var(--accent-color);
}

.download-btn {
  background-color: var(--primary-color);
}

.actions, .batch-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

@media (max-width: 768px) {
  .file-item, .result-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .file-preview, .result-preview {
    width: 100%;
    height: 150px;
    margin-right: 0;
    margin-bottom: 1rem;
  }
  
  .file-info, .result-info {
    width: 100%;
    margin-bottom: 1rem;
  }
}
</style>